<?php

namespace App\Console\Commands;

use App\Models\Constant\OrderConstant;
use App\Models\Order\Order;
use App\Models\User\LiPei;
use App\Models\User\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class AutoCheck extends Command
{

    protected $signature = 'check:auto {id?}';

    public function handle() {
        //Log::info('check:auto');
        $argc = $this->arguments();
        if(isset($argc['id'])){
            $orders = Order::where('id',$argc['id'])->get();
        }else{
            $orders = Order::where(['status'=>OrderConstant::STATUS_WAIT_AUTO_CHECK])->get();
        }

        foreach ($orders as $order) {
            $reasons = [];
            $user = User::where(['id'=>$order->user_id])->first();
            $lipi = LiPei::where('case_number',$order->case_number)->where('is_auto_check',2)->first();
            if(empty($lipi)){
                //未找到对应立案号，就是暂时没有对应的理赔数据进行对比，状态就不用动，在后台的”待审核“列表查看
                $reasons[] = '未找到对应立案号！';
                //$order->status = OrderConstant::STATUS_WAIT_AUTO_HUMAN_CHECK;

            }elseif (date('Y-m-d',strtotime($lipi->chu_xian_date))!=date('Y-m-d',strtotime($order->chu_xian_date))){
                $reasons[] = '出险时间错误！';
                $order->status = OrderConstant::STATUS_WAIT_AUTO_HUMAN_CHECK;
            }elseif ($lipi->baoxian_name!=$order->bao_xian_name){
                $reasons[] = '被保险人姓名错误！';
                $order->status = OrderConstant::STATUS_WAIT_AUTO_HUMAN_CHECK;
            } elseif ($lipi->car_number!=$order->car_number){
                $reasons[] = '车牌号错误！';
                $order->status = OrderConstant::STATUS_WAIT_AUTO_HUMAN_CHECK;
            }  elseif (round($lipi->loss_price,2)!=round($order->ding_sun_price,2)){
                $reasons[] = '定损金额错误！';
                $order->status = OrderConstant::STATUS_WAIT_AUTO_HUMAN_CHECK;
            } elseif ($lipi->is_cancel_case=='否' || empty($order->cancel_case_url)){
                $reasons[] = '未销案！';
                $order->status = OrderConstant::STATUS_WAIT_AUTO_HUMAN_CHECK;
            } elseif ($lipi->is_cancel_case=='是' && empty($order->cancel_case_url)){
                $reasons[] = '未上传销案证明！';
                $order->status = OrderConstant::STATUS_WAIT_AUTO_HUMAN_CHECK;
            } elseif(!$user->isFirstApply($order->id)){
                $reasons[] = '非第一次申请！';
                $order->status = OrderConstant::STATUS_WAIT_AUTO_HUMAN_CHECK;
            } else{
                $order->status = OrderConstant::STATUS_CHECK_PASS;
                $order->lipei_reason = null;
            }
            if(count($reasons)>0){
                $order->lipei_reason = implode('，', $reasons);
            }
            $order->save();
        }

        return 0;
    }
}
